package com.fy.login.internal;

import com.fy.login.Role;

import javax.security.auth.Subject;
import java.io.Serializable;
import java.security.Principal;
import java.util.Iterator;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;

/**
 * @author zhufeifei 2022/8/7
 **/

public class SimplePrincipal implements Principal, Serializable {

    private final Role role;

    public SimplePrincipal(String name) {
        Objects.requireNonNull(name);
        this.role = Role.of(name);
    }

    @Override
    public boolean implies(Subject subject) {
        Set<SimplePrincipal> set = subject.getPrincipals(SimplePrincipal.class);
        return !set.isEmpty() && set.contains(this);
    }

    @Override
    public String getName() {
        return role.name().toLowerCase(Locale.ROOT).concat("--");
    }

    @Override
    public String toString() {
        return getName();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SimplePrincipal principal = (SimplePrincipal) o;
        return role == principal.role;
    }

    @Override
    public int hashCode() {
        return getName().hashCode();
    }
}
